#pragma once
#include <vector>
#include <queue>
#include <thread>
#include <mutex>
#include <condition_variable>
#include <functional>
#include <future>
#include <atomic>
#include <chrono>
#include <string>
#include <stdexcept>
namespace common_component
{
    class ThreadPool
    {
    public:
        /**
         * @brief 线程优先级
         */
        enum class Priority
        {
            LOW = 0,
            NORMAL = 1,
            HIGH = 2,
            CRITICAL = 3
        };
        /**
         * @brief 构造函数
         * @param num_thread 初始化线程数（0=自动检测CPU核心数）
         * @param name 线程池名称
         */
        explicit ThreadPool(size_t num_thread = 0, const std::string &name = "ThreadPool");
        ~ThreadPool();
        /**
         * @brief 提交任务
         * @param f 任务函数
         * @param args 函数参数
         * @param priority 任务优先级
         * @return future对象用于获取结果
         */
        template <class F, class... Args>
        auto Submit(Priority priority, F &&f, Args &&...args)
            -> std::future<typename std::result_of<F(Args...)>::type>
        {
            using return_type = typename std::result_of<F(Args...)>::type;
            auto task = std::make_shared<std::packaged_task<return_type()>>(
                std::bind(std::forward<F>(f), std::forward<Args>(args)...));
            std::future<return_type> res = task->get_future();
            {
                std::unique_lock<std::mutex> lock(queue_mutex_);
                if (stop_)
                {
                    throw std::runtime_error("ThreadPool is stopped");
                }
                tasks_.emplace(priority, [task]()
                               { (*task)(); });
            }
            condition_.notify_one();
            return res;
        }
        /**
         * @brief 提交普通优先级任务(简化接口)
         */
        template <class F, class... Args>
        auto Submit(F &&f, Args &&...args) -> std::future<typename std::result_of<F(Args...)>::type>
        {
            return Submit(Priority::NORMAL, std::forward<F>(f), std::forward<Args>(args)...);
        }
        /**
         * @brief 批量提交任务
         */
        template <class F>
        void SubmitBatch(const std::vector<F> &tasks, Priority priority = Priority::NORMAL)
        {
            std::unique_lock<std::mutex> lock(queue_mutex_);
            for (const auto &task : tasks)
            {
                tasks_.emplace(priority, task);
            }
            condition_.notify_all();
        }
        /**
         * @brief 动态调整线程数
         */
        void Resize(size_t num_threads);

        /**
         * @brief 获取当前线程数
         */
        size_t GetThreadCount() const { return workers_.size(); }
        /**
         * @brief 获取待处理任务数
         */
        size_t GetPendingTaskCount() const
        {
            std::unique_lock<std::mutex> lock(queue_mutex_);
            return tasks_.size();
        }
        /**
         * @brief 获取活跃线程数量
         */
        size_t GetActiveThreadCount() const { return active_threads_; }
        /**
         * @brief 等待所有任务完成
         */
        void WaitAll();

        /**
         * @brief 优雅关闭线程池
         * @param wait_for_completion 是否等待当前任务完成
         */
        void Shutdown(bool wait_for_completion = true);

        /**
         * @brief 检查线程池是否已关闭
         */
        bool IsShutdown() const { return stop_.load(); }

        /**
         * @brief 清空任务队列
         */
        void Clear();
        /**
         * @brief 设置线程CPU亲和性
         * @param thread_index 线程索引
         * @param cpu_index cpu核心索引
         */
        void SetThreadAffinity(size_t thread_index, size_t cpu_index);
        /**
         * @brief 获取统计信息
         */
        struct Statistics
        {
            uint64_t total_tasks_executed;
            uint64_t total_tasks_failed;
            double average_wait_time_ms;
            double average_execution_time_ms;
            size_t current_queue_size;
            size_t max_queue_size;
        };
        Statistics GetStatistics() const { return stats_; }
        auto enqueue(std::function<void()> f) -> std::future<void>;

    private:
        /**
         * @brief 线程包装器
         */
        struct Task
        {
            Priority priority;
            std::function<void()> func;
            std::chrono::steady_clock::time_point submit_time;
            Task(Priority p, std::function<void()> f)
                : priority(p), func(f), submit_time(std::chrono::steady_clock::now())
            {
            }
            bool operator<(const Task &other) const { return priority < other.priority; }
        };
        /**
         * @brief 工作线程函数
         */
        void WorkerThread();
        std::string name_;                 // 线程池名称
        std::vector<std::thread> workers_; // 工作线程
        // 任务队列
        std::priority_queue<Task> tasks_;
        // 同步
        mutable std::mutex queue_mutex_;
        std::condition_variable condition_;
        std::condition_variable finish_condition_;
        // 状态
        std::atomic<bool> stop_{false};
        std::atomic<size_t> active_threads_{0};
        // 统计
        mutable Statistics stats_;
    };

} // namespace common_component